package com.edu.component;

import lombok.Data;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Data
public class QueryParam {
    private Integer limit = 10;
    private Integer page = 1;
    private Map<String,String> param = new HashMap();

    public QueryParam(){ }

	/* --代码(1)构造器-- */
    public QueryParam(HttpServletRequest req){
        //1.抓取limit 参数（页大小）[默认10条]
        this.limit = getInteger(req,"limit",10);
        //2.抓取page 参数（页大小）[默认为第1页]
        this.page = getInteger(req,"page",1);
        //3.抓取 其它的模糊搜索参数
        pickData( req.getParameterMap());
    }

    /* --代码(2)-- */
    private void pickData(Map<String, String[]> data) {
        //1.抓取其他的模糊搜索参数
        data.forEach((K,V)->{
            param.put(K,V[0]);
        });
        //2.移除掉map中特殊的关键字
        param.remove("limit");  //页大小
        param.remove("page");   //页码
        param.remove("ran");
    }



    private Integer getInteger(HttpServletRequest req,
          String key, Integer defVal) {
        String val = req.getParameter(key);
        if( val==null || val.length()==0 ){
            return defVal;
        }
        return Integer.valueOf( val );
    }

}
